/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.vanniktech.vntnumberpickerpreference.sample.slice;

import com.vanniktech.vntnumberpickerpreference.Constants;
import com.vanniktech.vntnumberpickerpreference.PreferenceUtils;
import com.vanniktech.vntnumberpickerpreference.sample.ResourceTable;
import com.vanniktech.vntnumberpickerpreference.sample.SettingsAbility;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Optional;

/**
 * MainAbilitySlice
 *
 * @since 2021-06-15
 */
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private static final int TWO = 2;
    private static final int TEN = 10;
    private static final int FOUR = 4;
    private static final int OFFSET = 130;
    private Text bodySizeTextView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initComponent();
        initData();
    }

    private void initComponent() {
        Image settingImage = (Image) findComponentById(ResourceTable.Id_settingImage);
        Text checkItOutOnGitHubTextView = (Text) findComponentById(ResourceTable.Id_check_it_out_on_github);
        bodySizeTextView = (Text) findComponentById(ResourceTable.Id_body_size);
        settingImage.setClickedListener(this);
        checkItOutOnGitHubTextView.setClickedListener(this);
    }

    private void initData() {
        bodySizeTextView.setText("Body size - " + PreferenceUtils.
            getString(getApplicationContext(), Constants.BODY_SIZE, "180"));
        bodySizeTextView.setTextSize(AttrHelper.vp2px(Integer.parseInt(PreferenceUtils.
            getString(getApplicationContext(), Constants.FONT_SIZE, "25")), getContext()));
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_settingImage:
                DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this)
                    .parse(ResourceTable.Layout_custom_setting_popup, null, false);
                Text textSetting = (Text) menuComponent.findComponentById(ResourceTable.Id_text);
                textSetting.setWidth(getWindow().getLayoutConfig().get().width / TWO);
                ShapeElement element = new ShapeElement();
                element.setCornerRadius(TEN);
                textSetting.setBackground(element);
                Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(this);
                DisplayAttributes displayAttributes = display.get().getAttributes();
                PopupDialog menuDialog = new PopupDialog(this, null);
                menuDialog.setCornerRadius(TEN);
                menuDialog.setCustomComponent(menuComponent);
                menuDialog.showOnCertainPosition(1, displayAttributes.width / FOUR
                    - AttrHelper.vp2px(TEN, getContext()), -displayAttributes.width + OFFSET);
                menuDialog.setAutoClosable(true);
                menuDialog.setAlignment(LayoutAlignment.RIGHT | LayoutAlignment.TOP);
                menuDialog.show();
                textSetting.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        menuDialog.destroy();
                        Intent intent = new Intent();
                        Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(getAbilityPackageContext().getBundleName())
                            .withAbilityName(SettingsAbility.class.getName())
                            .build();
                        intent.setOperation(operation);
                        startAbility(intent);
                    }
                });
                break;
            case ResourceTable.Id_check_it_out_on_github:
                initWeb(getUrl());
                break;
            default:
        }
    }

    /*
     * 浏览器
     * */
    private void initWeb(String urlString) {
        Intent intents = new Intent();
        Operation operation = new Intent.OperationBuilder()
            .withUri(Uri.parse(urlString))
            .withAction(IntentConstants.ACTION_SEARCH)
            .build();
        intents.setOperation(operation);
        startAbility(intents);
    }

    private String getUrl() {
        ohos.global.resource.ResourceManager resManager = this.getResourceManager();
        ohos.global.resource.RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/url.text");
        StringBuffer stringBuffer = new StringBuffer();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(rawFileEntry.openRawFile()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            return stringBuffer.toString();
        } catch (IOException e) {
            e.getMessage();
        }
        return "";
    }
}
